package top.kaoshanji.p1ch08a;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 代码清单-p1ch08a-148页a：SessionListener类
 * @author kaoshanji
 * ^_^
 * create time 2025/4/8 10:19
 */
@WebListener
public class SessionListener implements HttpSessionListener, ServletContextListener {

    // ServletContext 属性名
    private final static String SERVLET_CONTEXT_ATTRIBUTE_USER_COUNTER = "userCounter";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        servletContext.setAttribute(SERVLET_CONTEXT_ATTRIBUTE_USER_COUNTER, new AtomicInteger());
    }

    // 创建 HttpSession 时触发
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        ServletContext servletContext = session.getServletContext();

        AtomicInteger userCounter = (AtomicInteger)servletContext.getAttribute(SERVLET_CONTEXT_ATTRIBUTE_USER_COUNTER);
        int userCount = userCounter.incrementAndGet(); // 递增 1
        System.out.println("userCount incremented to :" + userCount);
    }

    // HttpSession 销毁时触发
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        ServletContext servletContext = session.getServletContext();

        AtomicInteger userCounter = (AtomicInteger)servletContext.getAttribute(SERVLET_CONTEXT_ATTRIBUTE_USER_COUNTER);
        int userCount = userCounter.decrementAndGet(); // 递减 1
        System.out.println("userCount decremented to :" + userCount);

    }

}
